package cn.lzj.ymcc.service.impl;

import cn.lzj.ymcc.constants.RocketMQConstants;
import cn.lzj.ymcc.doc.CourseDoc;
import cn.lzj.ymcc.domain.*;
import cn.lzj.ymcc.dto.CourseDto;
import cn.lzj.ymcc.dto.SendStation2MQDto;
import cn.lzj.ymcc.exception.GlobleException;
import cn.lzj.ymcc.feign.CourseESFeignClient;
import cn.lzj.ymcc.mapper.CourseMapper;
import cn.lzj.ymcc.result.JSONResult;
import cn.lzj.ymcc.service.*;
import cn.lzj.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zijia.liao
 * @since 2022-07-11
 */
@Slf4j
@Service
@Transactional
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private ICourseDetailService detailService;
    @Autowired
    private ICourseSummaryService courseSummaryService;
    @Autowired
    private ICourseMarketService courseMarketService;
    @Autowired
    private ICourseResourceService resourceService;
    @Autowired
    private ICourseTeacherService courseTeacherService;
    @Autowired
    private CourseESFeignClient courseESFeignClient;
    @Autowired
    private RocketMQTemplate mqTemplate;

    @Override
    public void save(CourseDto courseDto) {
        /**
         * 1.参数校验
         * 2.过滤条件---课程名称不能重复
         * 3.添加课程
         * 4.添加课程详情
         * 5.添加课程资源
         * 6.添加市CourseMarket
         */
        Course course = courseDto.getCourse();
        CourseDetail courseDetail = courseDto.getCourseDetail();
        CourseMarket courseMarket = courseDto.getCourseMarket();
        CourseResource courseResource = courseDto.getCourseResource();
        List<Long> teacharIds = courseDto.getTeacharIds();
        // 1.参数校验
       // 2.过滤条件---课程名称不能重复
        //2.1获取课程名称--封装个方法查询出课程名称
        //selectByname(course.getName());
/*        List<Course> courseList = selectList(null);
        for (Course course1 : courseList) {
            String courseNameforDB = course1.getName();
            if(courseNameforDB.equals(course.getName())){
                throw new GlobleException("课程名字重复！！请修改");} }*/
        Course courseFromDB = selectByname(course.getName());
        AssertUtil.isNull(courseFromDB, "课程名重复！！");


        //因为有些字段没有做链接，所以直接写假数据
        course.setLoginUserName("liaozijia");
        course.setStatus(0);
        course.setLoginId(1L);
        course.setOnlineTime(null);
        course.setChapterCount(0);
        insert(course);

        //查询老师列表
        List<Teacher> teachers = teacherService.selectBatchIds(teacharIds);
        //把老师对象集合变成名字  string集合 映射  List<String>
        List<String> tearherNameList = teachers.stream().map(teacher -> teacher.getName()).collect(Collectors.toList());
        //把集合中的元素使用某个符号拼接成
        String tearherNameStr = StringUtils.join(tearherNameList, ",");
        course.setTeacherNames(tearherNameStr);
        // 3.添加课程
        insert(course);

        //4.保存课程详情====
        courseDetail.setId(course.getId());
        detailService.insert(courseDetail);
        //5.保存课程营销---courseMarket
        courseMarket.setId(course.getId());
        courseMarketService.insert(courseMarket);
        //6.保存课程资源
        courseResource.setCourseId(course.getId());
        resourceService.insert(courseResource);
        //7.课程汇总 == courseSummary
        CourseSummary courseSummary = new CourseSummary();
        courseSummary.setId(course.getId());
        courseSummaryService.insert(courseSummary);
        //8.保存课程和老师的关系----中间表
        teacharIds.forEach(tid->{
            CourseTeacher courseTeacher = new CourseTeacher();
            courseTeacher.setTeacherId(tid);
            courseTeacher.setCourseId(course.getId());
            courseTeacherService.insert(courseTeacher);
        });

       // 4.添加课程详情
       // 5.添加课程资源
       // 6.添加市CourseMarket
    }

    /**
     * 课程上架的实现
     * 1.参数校验
     * 2.条件过滤
     * 3.添加到索引库
     * @param id
     */
    @Override
    public void onLineCourse(Long id) {

        //1.参数校验
        //AssertUtil.isEquals(id, id, "");
        AssertUtil.isNotNull(id,"非法的请求！！");
        // 2.条件过滤
        Course course = selectById(id);
        AssertUtil.isNotNull(course, "非法的请求！！");
        //AssertUtil.isTrue(course.equals(id), "已近上线了！！");
        AssertUtil.isEquals(course.getStatus(), 0, "课程已经上线！！");
        course.setStatus(1);

        //super.update(course, )
        course.setOnlineTime(new Date());
        super.updateById(course);
        // 4.调用feign的接口把数据保存早es的索引库中
        CourseDoc courseDoc = new CourseDoc();
        CourseMarket courseMarket = courseMarketService.selectById(course);
        CourseSummary courseSummary = courseSummaryService.selectById(course);

        BeanUtils.copyProperties(course, courseDoc);
        BeanUtils.copyProperties(courseMarket, courseDoc);
        BeanUtils.copyProperties(courseSummary, courseDoc);
        //单独处理收费的方式  1：收费  0：免费
        courseDoc.setChargeName(courseMarket.getCharge()==1?"收费":"免费");


        JSONResult jsonResult = courseESFeignClient.savees(courseDoc);
        AssertUtil.isTrue(jsonResult.isSuccess(), jsonResult.getMessage());
        SendMQMessage(course);

    }

    /**
     * 课程下架的逻辑
     * @param id
     */
    @Override
    public void offLineCourse(Long id) {


        //1.参数校验
        //AssertUtil.isEquals(id, id, "");
        AssertUtil.isNotNull(id,"非法的请求！！");
        // 2.条件过滤
        Course course = selectById(id);
        AssertUtil.isNotNull(course, "非法的请求！！");
        //2.条件判断--是否已经下架-已下架，返回全局异常=-不能重复下架
        AssertUtil.isEquals(course.getStatus(), 1, "课程已经下线！！");
        //3.修改数据库的上下架状态  1:上架 0：下架
        course.setStatus(0);
        course.setEndTime(new Date());
        super.updateById(course);
        //4.根据前端返回的id删除ES索引库里面的信息 --包括课程，课程资源，课程营销
        JSONResult jsonResult = courseESFeignClient.offLineCourse(id);
        AssertUtil.isTrue(jsonResult.isSuccess(), jsonResult.getMessage());
        log.info("下线成功");
    }

    public Course selectByname(String name){
        Wrapper<Course> coursename=new EntityWrapper<>();
        coursename.eq("name", name);
        return selectOne(coursename);
    }

    /**
     * MQ推送消息的逻辑
     */
    public void SendMQMessage(Course course){
        String sendStationMsg="课程为%s,点击此链接进入详情<a href='http://localhost:6002/detail.html?courseId=%s'>";
        String sendStationFormat = String.format(sendStationMsg, course.getName(), course.getId());

        SendStation2MQDto dto = new SendStation2MQDto("发布课程啦！！",sendStationFormat,"课程",Arrays.asList(1L,2L));


        SendResult sendResult = mqTemplate.syncSend(
                RocketMQConstants.ROKETMQ_TOPIC_STATION_SENDMQMEESAGE + ":" +
                        RocketMQConstants.ROKETMQ_TAGS_STATION_SENDMQMEESAGE,
                JSON.toJSONString(dto));
        log.info("推送站内信完成！！",sendResult);

    }
}
